import Dep from './dep'

export default class Observer {
	constructor(data) {
		this.walk(data)
	}

	walk(data) {
		if (!data || typeof data !== 'object') return

		Object.keys(data).forEach(key => {
			this.defineReactive(data, key, data[key])
		})
	}

	defineReactive(data, key, val) {
		const that = this
		const dep = new Dep()
		this.walk(val)
		Object.defineProperty(data, key, {
			configurable: true,
			enumerable: true,
			get() {
				if (Dep.target && Dep.target.update) {
					dep.addSub(Dep.target)
				}
				return val
			},
			set(newVal) {
				if (newVal === val) return
				val = newVal

				that.walk(newVal)
				dep.notify()
			},
		})
	}
}
